package com.example.musicplayer.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import com.example.musicplayer.commonUtils.DrawUtil;

public class CircleImageView extends androidx.appcompat.widget.AppCompatImageView {
    //画笔
    private final Paint mPaint;
    private final Matrix mMatrix;
    //圆形图片的半径
    private int mRadius;

    public CircleImageView(Context context) {
        this(context, null);
    }

    public CircleImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setSquareBitmap(null);
        mPaint = new Paint();
        mMatrix = new Matrix();
    }

    //截取图片的正中间部分
    public void setSquareBitmap(Bitmap bitmap) {
        if (bitmap == null) {
            bitmap = DrawUtil.getDefaultBitmap();
        }
        Bitmap result = bitmap;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int length = Math.min(width, height);
        int xTopLeft = (width - length) / 2;
        int yTopLeft = (height - length) / 2;
        try {
            result = Bitmap.createBitmap(bitmap, xTopLeft, yTopLeft, length, length);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        this.setImageBitmap(result);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //保持圆形图片宽高一致
        int size = Math.min(getMeasuredWidth(), getMeasuredHeight());
        //计算半径
        mRadius = size / 2;
        setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //设置抗锯齿
        mPaint.setAntiAlias(true);
        Drawable drawable = getDrawable();
        if (drawable != null) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            @SuppressLint("DrawAllocation") BitmapShader bitmapShader =
                    new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            //计算图片的缩放比例
            float scale = (mRadius * 2.0f) / Math.min(bitmap.getWidth(), bitmap.getHeight());
            mMatrix.setScale(scale, scale);
            bitmapShader.setLocalMatrix(mMatrix);
            mPaint.setShader(bitmapShader);
            //设置横纵坐标和圆形半径，给定画笔
            canvas.drawCircle((float) getWidth() / 2, (float) getHeight() / 2, mRadius, mPaint);
        } else {
            super.onDraw(canvas);
        }
    }
}